<?php
class Default_Service_Upload
{
	/**
	 * 递归创建路径
	 *
	 * @param
	 *       	 $path
	 */
	protected static function mkdirs($path)
	{
		if (! file_exists($path))
		{
			self::mkdirs(dirname($path));
			mkdir($path, 0777);
		}
	}
	/**
	 * 获取目录
	 *
	 * @param
	 *       	 $path
	 */
	public static function getdir($mkdir = false)
	{
		$now = date("Y/m/d/");
		$path = APPLICATION_PATH . '/../data/upload/' . $now;
		if ($mkdir)
		{
			self::mkdirs($path);
		}
		return array(
				"abPath" => $path,
				'path' => $now
		);
	}
	/**
	 * 缩略图
	 *
	 * @param $path 图片路径       	
	 * @param $name 图片名称       	
	 * @param $width 图片宽度       	
	 * @param $height 图片高度       	
	 * @param $bgcolor 图片背景颜色
	 *       	 @判断长和宽的长度，计算比例
	 */
	public static function mkThumb($res_path,  $width = 100, $height = 100, $bgcolor = "FFFFFF")
	{
		$org_info = @getimagesize($res_path);
		
		switch ($org_info[2])
		{
			case 1 :
			case 'image/gif' :
				$res = imagecreatefromgif($res_path);
				break;
					
			case 2 :
			case 'image/pjpeg' :
			case 'image/jpeg' :
			case 'image/jpg' :
				$res = imagecreatefromjpeg($res_path);
				break;
					
			case 3 :
			case 'image/x-png' :
			case 'image/png' :
				$res = imagecreatefrompng($res_path);
				break;
					
			default :
				return false;
		}
		
		$img_org = $res;
		
		/*
		 * 原始图片以及缩略图的尺寸比例
		 */
		$scale_org = $org_info[0] / $org_info[1];
		$img_thumb = imagecreatetruecolor($width, $height);
		$red = $green = $blue = "";
		sscanf($bgcolor, "%2x%2x%2x", $red, $green, $blue);
		$clr = imagecolorallocate($img_thumb, $red, $green, $blue);
		imagefilledrectangle($img_thumb, 0, 0, $width, $height, $clr);
		if ($org_info[0] / $width > $org_info[1] / $height)
		{
			$lessen_width = $width;
			$lessen_height = $width / $scale_org;
		} else
		{
			/*
			 * 原始图片比较高，则以高度为准
			 */
			$lessen_width = $height * $scale_org;
			$lessen_height = $height;
		}
		$dst_x = ($width - $lessen_width) / 2;
		$dst_y = ($height - $lessen_height) / 2;
		@imagecopyresampled($img_thumb, $img_org, $dst_x, $dst_y, 0, 0, $lessen_width, $lessen_height, $org_info[0], $org_info[1]);
		
		$thumb = "";
		if (function_exists('imagejpeg'))
		{
			$thumb .= '.thumb.jpg';
			imagejpeg($img_thumb, $res_path . $thumb, 100);
		} elseif (function_exists('imagegif'))
		{
			$thumb .= '.thumb.gif';
			imagegif($img_thumb, $res_path . $thumb);
		} elseif (function_exists('imagepng'))
		{
			$thumb .= '.thumb.png';
			imagepng($img_thumb, $res_path . $thumb);
		}
		imagedestroy($img_thumb);
		imagedestroy($img_org);
		
		return array("x"=>$dst_x,"y"=>$dst_y,"thumb"=>$thumb);
	}
	
}